package cn.he4966.ws.wss;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

@Component
@Slf4j
public class WebSocketHandler extends AbstractWebSocketHandler {

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        //socket连接成功后触发
        log.info("建立websocket连接");
//        WebSocketSessionManager.add(session.getId(), session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 客户端发送普通文件信息时触发
        log.info("发送文本消息");
        // 获得客户端传来的消息
        String payload = message.getPayload();
        log.info("服务端接收到消息 " + payload);
        // 发送消息给客户端

        String ip = session.getRemoteAddress().getAddress().getHostAddress();

        //{"action":"isupdate","group":"twssc"}
        //        用hutool判断字符串是否是json
        if(JSONUtil.isJson(payload)){
            //判断是否是json
            //如果是json
            //判断是否有group
            JSONObject json = JSONUtil.parseObj(payload);

            System.out.printf(json.getStr("group"));
            //如果有group字段
            if(json.containsKey("group")){
                String group = json.getStr("group");
                //把该用户加入到群组
                WebSocketService.addGroup(group,session);

                //给该群组发消息
                WebSocketService.groupMsg(group,payload);


                session.sendMessage(new TextMessage("{\"code\":1,\"ip\":"+ ip+"}"));
            }else{
                session.sendMessage(new TextMessage("{\"code\":0,\"ip\":"+ ip+",\"msg\":\"参数错误没group\"}"));
            }
        }else{
            session.sendMessage(new TextMessage("{\"code\":0,\"ip\":"+ ip+",\"msg\":\"参数错误\"}"));
        }



//       数据是json格式然后解析 判断是否有group
        if(payload.contains("group")){
//            String group = payload.split(":")[1];
//            WebSocketService.broadcastMsg(group);
        }

    }

    @Override
    protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) throws Exception {
        //客户端发送二进信息是触发
        log.info("发送二进制消息");
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        //异常时触发
        log.error("异常处理");
//        WebSocketSessionManager.removeAndClose(session.getId());

    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        // socket连接关闭后触发
        log.info("关闭websocket连接");
//        WebSocketSessionManager.removeAndClose(session.getId());
    }
}